package com.avic.rong.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.avic.rong.R;
import com.avic.rong.activity.mine.MyFansActivity;
import com.avic.rong.adapter.MyFansAdapter;
import com.avic.rong.api.focus_fans.FansApi;
import com.avic.rong.api.focus_fans.FocusStateApi;
import com.avic.rong.bean.focus_fans.FansBean;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.StringUtil;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class MyFensFragment extends BaseLazyFragment implements OnRefreshLoadMoreListener {


    @BindView(R.id.recycler_fens)
    RecyclerView recycler_fens;
    @BindView(R.id.srl_fans)
    SmartRefreshLayout srl_fans;
    private View view;
    private Unbinder unbinder;

    private String url;


    private int mPosition;

   // private String token = "w4/b+EQcZZmuYSosgIl6kjOihCikFMkqY2R3ecdjkOYLF2xTVRyFnfxTic0l1spUdbPKeCgcDT2lt0HxGkGr7kr+9zHAlRRT";

    private String loginToken;
    private MyFansAdapter myFansAdapter;
    private boolean isRefresh;
    private int pageNo = 1;
    private FansApi fansApi;
    private ArrayList<FansBean.ListBean>  mList = new ArrayList<>() ;

    private String homeUserId;
    private int pageSize = 10;
    private LoadingLayout loading_layout;

    public MyFensFragment() {
        // Required empty public constructor
    }

    private Context mContext;
    private String title;

    public static MyFensFragment getInstence(String title, String url, Context mContext, String homeUserID) {
        MyFensFragment myFensFragment = new MyFensFragment();
        myFensFragment.title = title;
        myFensFragment.mContext = mContext;
        myFensFragment.url = url;
        myFensFragment.homeUserId = homeUserID;
        return myFensFragment;
    }


    //该页面是否已经准备完毕(onCreateView调用完毕)
    private boolean isPrepared;
    //该fragment，是否已经执行过懒加载
    private boolean isLazyLoaded;


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (SharedPreferencesUtil.isLogin()){
            loginToken = SharedPreferencesUtil.getLoginToken();
        }
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_my_fens, container, false);
        unbinder = ButterKnife.bind(this, view);

        loading_layout = view.findViewById(R.id.loading_layout);
        loading_layout.setStatus(LoadingLayout.LOADING);


        loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                HttpManager.getInstance().doHttpDeal(fansApi);
                loading_layout.setStatus(LoadingLayout.LOADING);
            }

            @Override
            public void onReturn(View v) {
                getActivity().onBackPressed();
            }
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recycler_fens.setLayoutManager(linearLayoutManager);

        myFansAdapter = new MyFansAdapter(getContext(), mList, loginToken);
        recycler_fens.setAdapter(myFansAdapter);

        srl_fans.setOnRefreshLoadMoreListener(this);


        return view;
    }

    private void initData() {
        fansApi = new FansApi((MyFansActivity) getActivity(), fansListener);
        fansApi.setCache(false);
   /*     fansApi.setCancel(false);
        fansApi.setShowProgress(true);*/
        fansApi.setArgument(pageNo, pageSize, loginToken,homeUserId, url);
        HttpManager.getInstance().doHttpDeal(fansApi);
    }

    HttpOnNextListener<BaseResultEntity> fansListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                FansBean data = (FansBean) baseResultEntity.getData();
                List<FansBean.ListBean> list = data.getList();
                loading_layout.setStatus(LoadingLayout.SUCCESS);
                if (list!=null&&list.size()>0) {
                    if (isRefresh) {
                        mList.clear();
                    }

                    mList.addAll(list);
                    Log.e("MyFensFragment", "list: " + list.size());
                    Log.e("MyFensFragment", "mList: " + mList.size());

                    myFansAdapter.notifyDataSetChanged();
                }
                if (mList!=null&&mList.size()<=0){
                    loading_layout.setStatus(LoadingLayout.EMPTY);
                    loading_layout.setEmptyImageVisible(true);
                    loading_layout.setEmptyImage(R.mipmap.empty_foucs);
                    if (title.endsWith("关注")) {
                        if (StringUtil.isEmpty(homeUserId)) {
                            loading_layout.setEmptyText("您还未关注融融号~");
                        }else {
                            loading_layout.setEmptyText("TA还未关注融融号~");
                        }
                    }else {
                        loading_layout.setEmptyText("暂无粉丝~");
                    }
                }
                if (isRefresh) {
                    srl_fans.finishRefresh();
                } else {
                    srl_fans.finishLoadMore();
                }
            }else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

        isRefresh = false;
        pageNo = pageNo + 1;
        fansApi.setOffset(pageNo);
        HttpManager.getInstance().doHttpDeal(fansApi);

//        refreshLayout.finishLoadMore(2000);//传入false表示加载失败
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        isRefresh = true;
        pageNo = 1;
        fansApi.setOffset(pageNo);
        HttpManager.getInstance().doHttpDeal(fansApi);

//        refreshLayout.finishRefresh(2000);//传入false表示刷新失败
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void loadData() {
        initData();
    }
}
